<template>
    <el-card shadow="never">
        <div class="title_box">
            <div>趋势图</div>
            <div class="title_box_right">
                <el-date-picker
                    v-model="paramsechart.time"
                    class="custom-date-picker"
                    :clearable="false"
                    :default-time="[new Date(0, 0, 0, 0, 0, 0), new Date(0, 0, 0, 23, 59, 59)]"
                    type="daterange"
                    prefix-icon="Calendar"
                    range-separator="~"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    :disabled-date="disabledDate"
                    @change="onTimeChange" />
                <el-button class="export-btn" :disabled="!chartNum.length" @click="onExport">导出</el-button>
            </div>
        </div>
        <el-divider />
        <!-- <el-radio-group v-model="pageType" @change="onBtnChange">
            <el-radio-button :label="1">收集表份数</el-radio-button>
            <el-radio-button :label="2">填写人数</el-radio-button>
            <el-radio-button v-if="basic.jump_type == 1 && basic.jump_limit == 2" :label="3"
                >新增客户数</el-radio-button
            >
            <el-radio-button v-if="basic.jump_type == 2 && basic.jump_limit == 2" :label="4"
                >新增群用户数</el-radio-button
            >
        </el-radio-group> -->
        <div class="radio-group-box">
            <div
                v-for="item in radioGroupList"
                :key="item.type"
                class="radio-group-box-item"
                :class="{ 'radio-group-box-item-checked': paramsechart.type == item.type }"
                @click="handleRadioChange(item.type)">
                <span>{{ item.label }}</span>
                <span class="item-total">{{ item.total }}</span>
            </div>
        </div>
        <div v-if="chartNum.length" id="echarts" ref="myChartLineRef"></div>
        <el-empty v-else>
            <template #image>
                <img class="empty_img" src="@/assets/noData.png" alt="" />
            </template>
        </el-empty>
    </el-card>
</template>

<script setup lang="ts">
import {
    ref,
    inject,
    nextTick,
    watch,
    withDefaults,
    defineProps,
    defineEmits,
    reactive,
    computed,
    onMounted
} from 'vue';
import { export2Img, numFormat } from '@/utils/utils';
import { downFile, getDay, DFormat } from '@/utils/utils';
import { useRoute } from 'vue-router';
import { statchartList, collectStatisticsExport, statinfoList } from '@/api/highMaterial/collectionTable';
import { ShowTaskMessage } from '@/hooks/TaskMessageHooks';
import { parabolaAnimation } from '@/utils/parabola';
import dayjs from 'dayjs';

const route = useRoute();

interface Props {
    info: any;
}
const props = withDefaults(defineProps<Props>(), {
    info: () => {
        return {
            activity_name: '',
            period_type: 1,
            created_at: '',
            real_end_date: '',
            created_user: '',
            status_name: '',
            effect_time: ['', '']
            // last_update_time: ''
        };
    }
});

watch(
    () => props.info,
    val => {
        if (val) {
            if (val?.actual_end_time) {
                // 如果有结束时间，默认时间选择结束时间最近7天内
                const beforeDate = dayjs(val?.actual_end_time).subtract(6, 'day').format('YYYY-MM-DD 00:00:00');
                const afterDate = dayjs(val?.actual_end_time).format('YYYY-MM-DD 23:59:59');
                paramsechart.time = [beforeDate, afterDate];
            }
        }
        getBaseInfo();
        getstatchartListFun();
    }
);

const emit = defineEmits(['submit']);

const basicInfo = reactive({
    total_num: 0,
    people_num: 0,
    new_cust: 0,
    join_num: 0,
    jump_limit: null,
    jump_type: null
});
const radioGroupList = computed(() => {
    const list = [
        {
            total: numFormat(basicInfo?.total_num || 0),
            label: '收集表份数',
            type: 1
        },
        {
            total: numFormat(basicInfo?.people_num || 0),
            label: '填写人数',
            type: 2
        }
    ];
    if (basicInfo?.jump_limit == 2) {
        if (basicInfo?.jump_type == 1) {
            list.push({
                total: numFormat(basicInfo?.new_cust || 0),
                label: '新增客户数',
                type: 3
            });
        }
        if (basicInfo?.jump_type == 2) {
            list.push({
                total: numFormat(basicInfo?.join_num || 0),
                label: '新增群用户数',
                type: 4
            });
        }
    }
    return list;
});

const echarts: any = inject('ec');
const myChartLineRef = ref(null);
const onExport = e => {
    // export2Img(
    //     myChartLineRef.value,
    //     paramsechart.type == 1
    //         ? '收集表份数'
    //         : paramsechart.type == 2
    //         ? '填写人数'
    //         : paramsechart.type == 3
    //         ? '新增客户数'
    //         : '新增群用户数'
    // );
    collectStatisticsExport({ id: route.query.id, time: paramsechart.time, type: paramsechart.type }).then(() => {
        parabolaAnimation(e);
        const list = {
            1: '收集表份数',
            2: '填写人数',
            3: '新增客户数',
            4: '新增群用户数'
        };
        ShowTaskMessage(`${list[paramsechart.type]}数据导出异步任务创建成功`);
    });
};
const handleRadioChange = v => {
    paramsechart.type = v;
    // emit('submit', v);
    getstatchartListFun();
};

const onTimeChange = () => {
    getBaseInfo();
    getstatchartListFun();
};

const disabledDate = (time: Date) => {
    return time.getTime() > Date.now();
};
const chartTime = reactive([]);
const chartNum = reactive([]);
//趋势图传参
const paramsechart = reactive({
    id: route.query.id,
    time: [getDay(-6), getDay(0, true)],
    type: 1 //1-收集表份数 2-填写人数 3-新增客户数 4-进群人数,默认收集表份数
});
// 统计趋势图
const getstatchartListFun = () => {
    const params = {
        ...paramsechart
    };
    statchartList(params).then((res: any) => {
        // console.log('列表数据', res)
        chartTime.length = 0;
        chartNum.length = 0;
        chartTime.push(...(res?.time || []));
        chartNum.push(...(res?.data || []));
        nextTick(() => {
            getEchartsLine();
        });
    });
};

// 统计数据
const getBaseInfo = () => {
    statinfoList({ id: route.query.id, time: paramsechart.time }).then((res: any) => {
        Object.assign(basicInfo, res);
    });
};

const getEchartsLine = () => {
    const myChartLine = echarts?.init(myChartLineRef.value);
    const option = {
        color: ['#fa6c00'],
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'cross',
                label: {
                    backgroundColor: '#FF6B00'
                }
            }
        },
        grid: {
            top: '20%',
            left: '22px',
            right: '38px',
            bottom: '3%',
            containLabel: true
            // borderColor: '#012f4a',// 边框颜色
        },
        xAxis: {
            type: 'category',
            data: chartTime,
            boundaryGap: false,
            // axisTick: {
            //   show: false,
            //   alignWithLabel: true
            // },
            offset: 3
        },
        yAxis: {
            type: 'value',
            name: paramsechart.type == 1 ? '份' : '人',
            minInterval: 1,
            nameGap: 10, // y轴name与横纵坐标轴线的间距
            nameTextStyle: {
                padding: [0, 35, 10, 0] // 加上padding可以调整其位置
            },
            axisTick: {
                show: false
            },
            axisLabel: {
                color: '#969696'
            },
            splitLine: {
                lineStyle: {
                    type: 'line',
                    color: '#e8e8e8' // 分割线颜色
                }
            }
        },
        series: [
            {
                name:
                    paramsechart.type == 1
                        ? '收集表份数'
                        : paramsechart.type == 2
                        ? '填写人数'
                        : paramsechart.type == 3
                        ? '新增客户数'
                        : '新增群用户数',
                type: 'line',
                data: chartNum,
                smooth: true,
                symbol: 'circle',
                symbolSize: 0,
                areaStyle: {
                    normal: {
                        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                            { offset: 0, color: 'rgba(247, 222, 211)' },
                            { offset: 0.5, color: 'rgba(251, 230, 223)' },
                            { offset: 1, color: 'rgba(255, 255, 255)' }
                        ])
                    }
                },
                itemStyle: {
                    normal: {
                        borderWidth: 2,
                        color: '#FF9D23'
                    }
                },
                emphasis: {
                    // 鼠标 hover 时的样式
                    itemStyle: {
                        color: '#FF9D23', // hover 圆点颜色
                        borderColor: '#FF9D23', // hover 圆点边框颜色
                        borderWidth: 8
                    }
                }
            }
        ]
    };
    myChartLine.setOption(option);
    nextTick(() => {
        myChartLine.resize();
    });
    window.onresize = function () {
        myChartLine.resize();
    };
};

onMounted(() => {
    // getBaseInfo();
    // getstatchartListFun();
});
</script>

<style lang="scss" scoped>
.title_box {
    display: flex;
    justify-content: space-between;
    align-items: center;

    &_right {
        display: flex;
        align-items: center;

        .export-btn {
            margin-left: 12px;
        }

        :deep(.custom-date-picker) {
            width: 260px;
        }
    }
}

.el-divider {
    margin-top: 18px;
    margin-bottom: 24px;
}

#echarts {
    display: flex;
    justify-content: center;
    height: 320px;
}

.empty_img {
    transform: translateX(13%);
}

.radio-group-box {
    display: flex;
    padding: 0 15px;

    &-item {
        /* max-width: 500px; */
        flex: 1;
        display: flex;
        align-items: flex-start;
        justify-content: space-between;
        height: 100px;
        border: 1px solid #e7e7e7;
        flex-direction: column;
        border-radius: 3px;
        margin: 0 10px;
        cursor: pointer;
        transition: color 0.3s;
        padding: 15px 20px;
        box-sizing: border-box;

        &-checked {
            background-color: #fffaf7;
            border-color: #ff6b00;
            color: #ff6b00;
        }

        &:hover {
            color: #ff6b00;
        }

        .item-total {
            font-size: 30px;
        }
    }
}

#echarts {
    padding: 0 30px;
}
</style>
